<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <el-row v-if="!detailVisible" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['deviceInfo:deviceInfo:export']"
        >
          导出
        </el-button>
      </el-col>
    </el-row>

    <!-- 卡片和图表容器 -->
    <div class="card-chart-container" v-if="!detailVisible">
      <div class="card-container">
        <el-card
            v-for="item in deviceInfoList"
            :key="item.id"
            class="device-card"
            :body-style="{ padding: '30px' }"
        >
          <div class="device-info">
            <div><strong>设备名称:</strong> {{ item.deviceName }}</div>
            <div><strong>所属测点:</strong> {{ item.monitorId }}</div>
            <div><strong>设备型号:</strong> {{ item.sensorModel }}</div>
            <div><strong>供应商:</strong> {{ item.sensorBrand }}</div>
            <div><strong>设备SN:</strong> {{ item.deviceSn }}</div>
            <div><strong>固件版本号:</strong> {{ item.firmwareVersion }}</div>
            <div><strong>通讯状态:</strong> {{ item.commStatus }}</div>
            <div><strong>数据状态:</strong> {{ item.dataStatus }}</div>
            <div><strong>接入协议:</strong> {{ item.protocol }}</div>
            <div><strong>数据时间:</strong> {{ parseTime(item.updateTime, "{y}-{m}-{d}") }}</div>
            <div><strong>物联网卡ICCID:</strong> {{ item.iccid }}</div>
          </div>
        </el-card>
      </div>

      <!-- 图表 -->
      <div id="chart" ref="chartRef" class="chart-container"></div>
    </div>

    <!-- 分页 -->
    <!-- 在这里可以添加分页组件 -->
  </div>
</template>

<script setup name="DeviceInfo">
import { listDeviceInfo } from "@/api/slope/device/deviceInfo/deviceInfo";
import { listSensor } from "@/api/slope/device/sensor/sensor.js";
import * as echarts from 'echarts';
import { onMounted, onUnmounted, watch, ref, nextTick, reactive, toRefs, getCurrentInstance, defineProps } from 'vue';

const chartRef = ref(null);
let chartInstance = null;
const { proxy } = getCurrentInstance();
const deviceSensors = ref([]);
const deviceInfoList = ref([]);
const loading = ref(true);
const total = ref(0);
const detailVisible = ref(false);

const props = defineProps({
  device: {
    type: Object,
    default: () => ({})
  }
});

const data = reactive({
  form: {},
  queryParams: {
    deviceSn: props.device.deviceSn,
    sensorId: null,
  },
});

const { queryParams } = toRefs(data);

async function getList() {
  loading.value = true;
  try {
    const [sensorRes, deviceRes] = await Promise.all([
      listSensor(queryParams.value),
      listDeviceInfo(queryParams.value)
    ]);

    deviceSensors.value = sensorRes.rows.map(sensor => sensor.sensorCode);
    deviceInfoList.value = deviceRes.rows;
    total.value = deviceRes.total;
  } catch (error) {
    console.error("获取数据失败：", error);
  } finally {
    loading.value = false;
  }
}

function initChart() {
  if (!chartRef.value) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartRef.value);
  window.addEventListener('resize', chartResize);

  const rootDeviceName = deviceInfoList.value.length > 0
      ? deviceInfoList.value[0].deviceName
      : '未知设备';

  const deviceSensorData = [{ deviceName: rootDeviceName, sensors: deviceSensors.value }];
  const nodes = [], links = [], nodeMap = new Map();
  let idx = 0;

  deviceSensorData.forEach(device => {
    nodes.push({
      id: `d${idx}`,
      name: device.deviceName,
      category: 0,
      symbolSize: 60
    });
    nodeMap.set(device.deviceName, `d${idx}`);
    idx++;

    device.sensors.forEach(sensor => {
      if (!nodeMap.has(sensor)) {
        nodes.push({
          id: `s${idx}`,
          name: sensor,
          category: 1,
          symbolSize: 40
        });
        nodeMap.set(sensor, `s${idx}`);
        idx++;
      }

      links.push({
        source: nodeMap.get(device.deviceName),
        target: nodeMap.get(sensor)
      });
    });
  });

  const option = {
    title: { text: '设备与传感器关联图', left: 'center' },
    tooltip: { formatter: '{b}' },
    legend: [{ data: ['设备', '传感器'], bottom: 0 }],
    toolbox: {
      show: true,
      orient: 'horizontal',
      left: 'left',
      top: 'top',
      feature: {
        saveAsImage: { show: true, title: '保存为图片' },
        restore: { show: true, title: '重置视图' },
        dataZoom: {
          show: true,
          title: { zoom: '区域缩放', back: '取消缩放' }
        },
        dataView: {
          show: true,
          title: '数据视图',
          readOnly: true,
          optionToContent(opt) {
            const nodes = opt.series[0].data;
            let table = `<table style="width:100%;text-align:left;border-collapse:collapse;" border="1">
              <thead><tr><th>名称</th><th>类型</th><th>节点ID</th></tr></thead><tbody>`;
            nodes.forEach(item => {
              table += `<tr><td>${item.name}</td><td>${item.category === 0 ? '设备' : '传感器'}</td><td>${item.id}</td></tr>`;
            });
            return table + `</tbody></table>`;
          }
        }
      }
    },
    series: [{
      type: 'graph',
      layout: 'circular',
      categories: [{ name: '设备' }, { name: '传感器' }],
      data: nodes,
      links: links,
      label: { show: true, position: 'right' },
      lineStyle: { color: 'source', curveness: 0 },
      emphasis: {
        focus: 'adjacency',
        lineStyle: { width: 3 }
      }
    }]
  };

  chartInstance.setOption(option);
}

function chartResize() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', chartResize);
});

watch(deviceInfoList, () => {
  nextTick(() => {
    initChart();
  });
});

function handleExport() {
  proxy.download('deviceInfo/deviceInfo/export', {
    ...queryParams.value
  }, `deviceInfo_${new Date().getTime()}.xlsx`);
}

onMounted(() => {
  getList();
});
</script>


<style scoped>
.card-chart-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  justify-content: center;
  margin-top: 20px;
}

.card-container {
  width: 50%; /* 每个卡片占50%的宽度 */
}

.device-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #fff;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.chart-container {
  width: 50%;
  height: 600px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}
</style>
